<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>公共请求头</title>
    <link href="/static/bootstrap-5.3.0-alpha1-dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="/docs/css/style.css">
    <style>
        .card {
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            border: none;
            border-radius: 12px;
        }
        
        .card-header {
            background: #fff;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            padding: 1rem 1.25rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .card-header h5 {
            color: #2c3e50;
            font-weight: 600;
            margin: 0;
        }

        .header-item {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border: 1px solid rgba(0,0,0,0.05);
            position: relative;
        }

        .header-item:last-child {
            margin-bottom: 0;
        }

        .header-item .form-control {
            border-color: rgba(0,0,0,0.1);
            position: relative;
        }

        .header-item .form-control:focus {
            border-color: #2196F3;
            box-shadow: none;
            background-color: #fff;
        }

        .header-actions {
            display: flex;
            gap: 0.5rem;
        }

        .btn-icon {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }

        .header-description {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.5rem;
        }

        .empty-state {
            text-align: center;
            padding: 2rem;
            color: #64748b;
        }

        .empty-state i {
            font-size: 2rem;
            margin-bottom: 1rem;
            color: #94a3b8;
        }

        /* 下拉列表样式 */
        .dropdown-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: #fff;
            border: 1px solid rgba(0,0,0,0.1);
            border-radius: 6px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            z-index: 1050;
            display: none;
            margin-top: 8px;
        }

        /* 下拉列表内容容器 */
        .dropdown-content {
            max-height: 200px;
            overflow-y: auto;
            padding: 4px 0;
        }

        /* 下拉列表三角形指示器 */
        .dropdown-list::before,
        .dropdown-list::after {
            content: '';
            position: absolute;
            left: 12px;
            border: solid transparent;
        }

        .dropdown-list::before {
            top: -18px;
            border-bottom-color: rgba(0,0,0,0.1);
            border-width: 9px;
        }

        .dropdown-list::after {
            top: -17px;
            border-bottom-color: #fff;
            border-width: 9px;
            margin-left: 0.5px;
        }

        .dropdown-item {
            padding: 8px 12px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #2c3e50;
            transition: all 0.2s ease;
        }

        .dropdown-item:hover {
            background: #f1f5f9;
        }

        .dropdown-item .label {
            font-weight: 500;
            color: #1e293b;
        }

        .dropdown-item .description {
            font-size: 0.85rem;
            color: #64748b;
            margin-left: 8px;
            opacity: 0.8;
        }

        .dropdown-item:hover .description {
            opacity: 1;
        }

        .input-wrapper {
            position: relative;
            z-index: 2;
        }

        /* 美化滚动条 */
        .dropdown-list::-webkit-scrollbar {
            width: 6px;
        }

        .dropdown-list::-webkit-scrollbar-track {
            background: transparent;
        }

        .dropdown-list::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .dropdown-list::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }
    </style>
</head>
<body>
    <div class="card">
        <div class="card-header">
            <h5>公共请求头</h5>
            <button class="btn btn-primary btn-sm" id="addHeader">
                <i class="fa fa-plus me-1"></i>添加请求头
            </button>
        </div>
        <div class="card-body">
            <div id="headerList">
                <!-- 请求头列表将动态插入这里 -->
            </div>
            <div class="empty-state" id="emptyState" style="display: none;">
                <i class="fa fa-inbox"></i>
                <p class="mb-0">暂无配置的请求头</p>
            </div>
        </div>
    </div>

    <!-- 请求头项模板 -->
    <template id="headerItemTemplate">
        <div class="header-item" data-id="">
            <div class="row g-2">
                <div class="col-md-4">
                    <div class="input-wrapper">
                        <input type="text" class="form-control header-key" 
                               placeholder="选择或输入 Header Key"
                               autocomplete="off">
                        <div class="dropdown-list key-dropdown">
                            <div class="dropdown-content">
                                <!-- 下拉选项将被插入这里 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="input-wrapper">
                        <input type="text" class="form-control header-value" 
                               placeholder="Header Value"
                               autocomplete="off">
                        <div class="dropdown-list value-dropdown"></div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="header-actions">
                        <button class="btn btn-outline-danger btn-icon delete-header">
                            <i class="fa fa-trash"></i>
                        </button>
                        <button class="btn btn-outline-primary btn-icon save-header">
                            <i class="fa fa-save"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="header-description">
                <!-- 描述信息将根据key自动更新 -->
            </div>
        </div>
    </template>

    <script src="/static/jquery-3.5.1/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function() {
            const STORAGE_KEY = 'api_headers';
            const headerOptions = [
                { key: 'Accept', desc: '接受的内容类型' },
                { key: 'Accept-Language', desc: '接受的语言' },
                { key: 'Authorization', desc: '身份验证令牌' },
                { key: 'Cache-Control', desc: '缓存控制' },
                { key: 'Content-Type', desc: '内容类型' },
                { key: 'Cookie', desc: '会话Cookie信息' },
                { key: 'Origin', desc: '请求源' },
                { key: 'Referer', desc: '请求来源' },
                { key: 'User-Agent', desc: '用户代理' },
                { key: 'X-Requested-With', desc: '请求方式' },
                { key: 'X-Request-ID', desc: '请求ID' },
                { key: 'X-CSRF-TOKEN', desc: 'CSRF令牌' }
            ];

            const headerDescriptions = {
                'Accept': '接受的内容类型，如：application/json',
                'Accept-Language': '接受的语言，如：zh-CN,zh;q=0.9,en;q=0.8',
                'Authorization': '身份验证token，格式：Bearer {token}',
                'Cache-Control': '缓存控制，如：no-cache',
                'Content-Type': '请求内容类型，默认：application/json',
                'Cookie': '会话Cookie信息',
                'Origin': '请求源，如：https://example.com',
                'Referer': '请求来源页面的URL',
                'User-Agent': '用户代理标识',
                'X-Requested-With': 'XMLHttpRequest用于标识AJAX请求',
                'X-Request-ID': '请求追踪ID',
                'X-CSRF-TOKEN': '跨站请求伪造保护令牌'
            };

            const headerValueExamples = {
                'Accept': [
                    { value: 'application/json', label: 'JSON格式' },
                    { value: 'application/xml', label: 'XML格式' },
                    { value: 'text/html', label: 'HTML格式' },
                    { value: '*/*', label: '所有格式' }
                ],
                'Accept-Language': [
                    { value: 'zh-CN', label: '中文' },
                    { value: 'en-US', label: '英文' },
                    { value: 'zh-CN,zh;q=0.9,en;q=0.8', label: '中文优先' }
                ],
                'Authorization': [
                    { value: 'Bearer {token}', label: 'Bearer认证' },
                    { value: 'Basic {base64}', label: 'Basic认证' }
                ],
                'Cache-Control': [
                    { value: 'no-cache', label: '不缓存' },
                    { value: 'no-store', label: '不存储' },
                    { value: 'max-age=0', label: '立即过期' },
                    { value: 'private', label: '私有缓存' }
                ],
                'Content-Type': [
                    { value: 'application/json', label: 'JSON数据' },
                    { value: 'application/x-www-form-urlencoded', label: '表单数据' },
                    { value: 'multipart/form-data', label: '文件上传' }
                ],
                'Origin': [
                    { value: 'http://localhost:8000', label: '本地开发' },
                    { value: 'https://example.com', label: '生产环境' }
                ],
                'User-Agent': [
                    { value: 'Mozilla/5.0', label: '浏览器' },
                    { value: 'PostmanRuntime/7.32.3', label: 'Postman' }
                ],
                'X-Requested-With': [
                    { value: 'XMLHttpRequest', label: 'AJAX请求' }
                ]
            };

            // 加载保存的请求头
            function loadHeaders() {
                const headers = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
                $('#headerList').empty();
                
                if (Object.keys(headers).length === 0) {
                    $('#emptyState').show();
                } else {
                    $('#emptyState').hide();
                    Object.entries(headers).forEach(([key, value]) => {
                        addHeaderItem(key, value);
                    });
                }
            }

            // 添加请求头项
            function addHeaderItem(key = '', value = '') {
                const template = document.getElementById('headerItemTemplate');
                const clone = document.importNode(template.content, true);
                const item = $(clone).find('.header-item');
                
                item.attr('data-id', Date.now());
                const keyInput = item.find('.header-key');
                const valueInput = item.find('.header-value');
                
                // 设置key和value
                keyInput.val(key);
                valueInput.val(value);
                
                // 更新描述和下拉列表
                updateDescription(item, key);
                if (key) {
                    handleValueDropdown(valueInput, key);
                }
                
                $('#headerList').append(item);
                $('#emptyState').hide();
                
                // 绑定事件
                keyInput.on('input focus', function() {
                    handleKeyDropdown($(this));
                });
                
                valueInput.on('input focus', function() {
                    const currentKey = keyInput.val().trim();
                    if (currentKey) {
                        handleValueDropdown($(this), currentKey);
                    }
                });
            }

            // 更新描述信息
            function updateDescription(item, key) {
                const description = headerDescriptions[key] || '自定义请求头';
                item.find('.header-description').text(description);
            }

            // 保存所有请求头
            function saveHeaders() {
                const headers = {};
                $('.header-item').each(function() {
                    const key = $(this).find('.header-key').val().trim();
                    const value = $(this).find('.header-value').val().trim();
                    if (key && value) {
                        headers[key] = value;
                    }
                });
                
                try {
                    localStorage.setItem(STORAGE_KEY, JSON.stringify(headers));
                    showAlert('请求头配置已保存', 'success');
                } catch (error) {
                    showAlert('保存失败', 'danger');
                }
            }

            // 事件绑
            $('#addHeader').on('click', function() {
                addHeaderItem();
            });

            $(document).on('click', '.delete-header', function() {
                const item = $(this).closest('.header-item');
                item.fadeOut(300, function() {
                    item.remove();
                    if ($('.header-item').length === 0) {
                        $('#emptyState').show();
                    }
                    saveHeaders();
                });
            });

            $(document).on('click', '.save-header', function() {
                saveHeaders();
            });

            $(document).on('input', '.header-key', function() {
                const item = $(this).closest('.header-item');
                const key = $(this).val().trim();
                const valueInput = item.find('.header-value');
                
                updateDescription(item, key);
                updateValueDatalist(key, valueInput);
            });

            // 初始化
            loadHeaders();

            // 如果没有配置，添加默认的请求头
            if ($('.header-item').length === 0) {
                addHeaderItem('Authorization', 'Bearer {token}');
                addHeaderItem('Content-Type', 'application/json');
                saveHeaders();
            }

            // 处理键的下拉列表
            function handleKeyDropdown(input) {
                const dropdown = input.closest('.input-wrapper').find('.key-dropdown');
                const searchTerm = input.val().toLowerCase();
                
                // 过滤匹配的选项
                let matchedOptions = headerOptions;
                
                // 如果有输入内容则进行过滤
                if (searchTerm) {
                    matchedOptions = headerOptions.filter(opt => 
                        opt.key.toLowerCase().includes(searchTerm) || 
                        opt.desc.toLowerCase().includes(searchTerm)
                    );
                }
                
                if (matchedOptions.length) {
                    const content = dropdown.find('.dropdown-content').empty();
                    matchedOptions.forEach(opt => {
                        content.append(`
                            <div class="dropdown-item" data-key="${opt.key}">
                                <span class="label">${opt.key}</span>
                                <span class="description">${opt.desc}</span>
                            </div>
                        `);
                    });
                    dropdown.show();
                } else {
                    dropdown.hide();
                }
            }

            // 处理值的下拉列表
            function handleValueDropdown(input, key) {
                const dropdown = input.closest('.input-wrapper').find('.value-dropdown');
                const examples = headerValueExamples[key];
                const searchTerm = input.val().toLowerCase();
                
                if (examples) {
                    let matchedExamples = examples;
                    
                    // 如果有输入内容则进行过滤
                    if (searchTerm) {
                        matchedExamples = examples.filter(ex => 
                            ex.value.toLowerCase().includes(searchTerm) || 
                            ex.label.toLowerCase().includes(searchTerm)
                        );
                    }
                    
                    dropdown.empty();
                    matchedExamples.forEach(example => {
                        dropdown.append(`
                            <div class="dropdown-item" data-value="${example.value}">
                                <span class="label">${example.value}</span>
                                <span class="description">${example.label}</span>
                            </div>
                        `);
                    });
                    dropdown.show();
                } else {
                    dropdown.hide();
                }
            }

            // 绑定输入事件
            $(document).on('input focus', '.header-key', function() {
                // 先隐藏所有其他的下拉列表
                $('.dropdown-list').not($(this).closest('.input-wrapper').find('.dropdown-list')).hide();
                handleKeyDropdown($(this));
            });

            // 选择键
            $(document).on('click', '.key-dropdown .dropdown-item', function() {
                const input = $(this).closest('.input-wrapper').find('input');
                const key = $(this).data('key');
                input.val(key);
                $(this).closest('.dropdown-list').hide();
                
                // 更新描述和值的下拉列表
                const item = input.closest('.header-item');
                const valueInput = item.find('.header-value');
                updateDescription(item, key);
                handleValueDropdown(valueInput, key);
                // 聚焦值输入框
                valueInput.focus();
            });

            // 选择值
            $(document).on('click', '.value-dropdown .dropdown-item', function() {
                const input = $(this).closest('.input-wrapper').find('input');
                input.val($(this).data('value'));
                $(this).closest('.dropdown-list').hide();
                // 自动保存
                input.closest('.header-item').find('.save-header').click();
            });

            // 点击其他地方关闭下拉列表
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.input-wrapper').length) {
                    $('.dropdown-list').hide();
                }
            });

            // 输入框失去焦点时检查是否需要隐藏下拉列表
            $(document).on('blur', '.header-key, .header-value', function() {
                const $this = $(this);
                setTimeout(() => {
                    // 检查新的焦点元素是否在同一个下拉列表内
                    const $newFocus = $(document.activeElement);
                    const $dropdown = $this.closest('.input-wrapper').find('.dropdown-list');
                    if (!$newFocus.closest('.dropdown-list').is($dropdown)) {
                        $dropdown.hide();
                    }
                }, 100);
            });
        });

        // Toast提示
        function showAlert(message, type) {
            try {
                const parentDoc = window.parent.document;
                let toast = parentDoc.getElementById('toast');
                const toastBody = toast.querySelector('.toast-body');
                
                toast.className = `toast align-items-center text-white bg-${type} border-0`;
                toastBody.textContent = message;
                
                const bsToast = new window.parent.bootstrap.Toast(toast, {
                    delay: 3000
                });
                bsToast.show();
            } catch (error) {
                console.error('Toast显示失败:', error);
                alert(message);
            }
        }

        // 更新值的提示列表
        function updateValueDatalist(key, valueInput) {
            const examples = headerValueExamples[key];
            if (examples) {
                // 为每个值输入框创建唯一的datalist
                const datalistId = `valueList_${Date.now()}`;
                let datalist = $(`<datalist id="${datalistId}"></datalist>`);
                examples.forEach(example => {
                    datalist.append(`<option value="${example.value}">${example.label}</option>`);
                });
                
                // 移旧的datalist（如存在）
                const oldDatalistId = valueInput.attr('list');
                if (oldDatalistId) {
                    $(`#${oldDatalistId}`).remove();
                }
                
                // 添加新的datalist
                $('body').append(datalist);
                valueInput.attr('list', datalistId);
                
                // 添加placeholder提示
                valueInput.attr('placeholder', `例如: ${examples[0].value}`);
            } else {
                // 如果没有预设值，移除datalist
                valueInput.removeAttr('list');
                valueInput.attr('placeholder', 'Header Value');
            }
        }
    </script>
</body>
</html> 